﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicalCare.DbLayer.Adaptors;
using MedicalCare.Messages;
using MedicalCare.Translator;
using StructureMap;
using MedicalCare.EntityDefinitions.Entities;
using MedicalCare.Utilities;

namespace MedicalCare.Admin
{
    public partial class AdminSchedule : System.Web.UI.Page
    {
        private static DateTime CanledarSelectDate = DateTime.Now.Date;
        private const string OrderKey = "fam.Name";
        private const string OrderValue = "DESC";
        private string _whereString = "1=1";
        private IList<UserEntity> nurseList;
        private IList<ddlItem> timeList;
        private IList<DateTime> bookedDateList
        {
            get
            {
                return (List<DateTime>)(ViewState["bookedDateList"]);
            }
            set { ViewState["bookedDateList"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                CalendarSchedule.VisibleDate = DateTime.Today;
                CalendarSchedule.SelectedDate = DateTime.Today;
                if (string.IsNullOrEmpty(tbLoopEndDay.Text))
                    tbLoopEndDay.Text = DateTime.Today.ToShortDateString();
                
                tbLoopEndDay.Attributes.Add("readonly", "true");   
                HiddenSchedule();

                InitialTime();
                InitialNurseList();
                InitialSchedule();

                InitialCalendar();
            }
        }
      
        private void CreateNewSchedule()
        {
            InitialTime();
            InitialNurseList();
            InitialNewScduleList();
        }

        private void ShowSchedule()
        {
            ScheduleList.Visible = true;
            btnShowNewSchedule.Visible = false;
        }
        
        private void HiddenSchedule()
        {
            ScheduleList.Visible = false;
            if (CanledarSelectDate < DateTime.Now.Date)
            {
                btnShowNewSchedule.Visible = false;
                lblLoopEndDay.Visible = false;
                tbLoopEndDay.Visible = false;
            }
            else
            {
                btnShowNewSchedule.Visible = true;
            }
        }

        private void ShowAddFamily()
        {
            panelAddFamily.Visible = true;
            btnSetPerson.Text = "取消添加其他病人";
        }

        private void HiddenAddFamily()
        {
            panelAddFamily.Visible = false;
            btnSetPerson.Text = "添加其他病人";
        }
        
        private void InitialTime()
        {
            timeList = new List<ddlItem>();
            var dt = DateTime.Today;
            var endTime = 18;
            timeList.Add(new ddlItem(" ", "-1"));
            for (int startTime = 8; startTime <= endTime; startTime++)
            {
                timeList.Add(new ddlItem(startTime + ":00", startTime.ToString()));
            }
        }
        
        private void InitialNurseList()
        {
            var userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            nurseList = new List<UserEntity>();
            nurseList = userAdaptor.GetUsers("Name", "DESC", " RoleCode = 'NURSE' ");
            nurseList.Add(new UserEntity() { Name = "请选择", Id = -1 });
        }

        private void InitialSchedule()
        {
            var message = new ScheduleMessage()
            {
                Date = CalendarSchedule.SelectedDate.Date
            };
            var scheduleList = CheckSchedule(message);
            if (scheduleList.Count > 0)
            {
                // 显示已存在的schedule
                var objPds = new PagedDataSource { DataSource = scheduleList };
                ScheduleList.DataSource = objPds;
                ScheduleList.DataBind();
            }
        }

        private IList<ScheduleEntity> CheckSchedule(ScheduleMessage message)
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();

            _whereString = " ScheduleDay = '" + message.Date + "' ";
            var scheduleEntityList = scheduleAdaptor.GetSchedule(OrderKey, OrderValue, _whereString);
            if (scheduleEntityList.Count > 0)
                ShowSchedule();
            else
                HiddenSchedule();
            return scheduleEntityList;
        }

        private void InitialNewScduleList()
        {
            var translator = ObjectFactory.GetInstance<IFamilyListToScheduleList>();
            var familyAdaptor = ObjectFactory.GetInstance<IFamilyAdaptor>();
            _whereString = "1=1";
            var source = translator.Translate(familyAdaptor.GetFamily(OrderKey, OrderValue, _whereString));
            var objPds = new PagedDataSource { DataSource = source};
            ScheduleList.DataSource = objPds;
            ScheduleList.DataBind();
        }

        private void InitialCalendar()
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();
            var displayDate = CalendarSchedule.VisibleDate;

            bookedDateList = scheduleAdaptor.GetAllBookedDatebyMonth(displayDate);
        }

        private void InitialFamilyList()
        {
            var familyAdaptor = ObjectFactory.GetInstance<IFamilyAdaptor>();
            var date = CalendarSchedule.SelectedDate.Date;
            _whereString = "fam.id not in (select familyid from schedule where ScheduleDay = '" + date + "' )";
            var source = familyAdaptor.GetFamily(OrderKey, OrderValue, _whereString);
            Familylist.DataValueField = "Id";
            Familylist.DataTextField = "Name";
            Familylist.DataSource = source;
            Familylist.DataBind();

        }

        protected void ScheduleList_ItemCommand(object source, DataListCommandEventArgs e)
        {

        }

        protected void ScheduleList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            var lbNurseId = (Label)(e).Item.FindControl("lbNurseId");
            var lbStartDT = (Label)(e).Item.FindControl("lbStartDT");
            var lbEndDT = (Label)(e).Item.FindControl("lbEndDT");

            var ddlNurse = (DropDownList)e.Item.FindControl("ddlNurse");
            ddlNurse.DataSource = nurseList;
            ddlNurse.DataBind();
            ddlNurse.SelectedValue = lbNurseId.Text;

            var ddlStartTime = (DropDownList)e.Item.FindControl("ddlStartTime");
            ddlStartTime.DataSource = timeList;
            ddlStartTime.DataBind();
            ddlStartTime.SelectedValue = DateTime.Parse(lbStartDT.Text).Hour.ToString();

            var ddlEndTime = (DropDownList)e.Item.FindControl("ddlEndTime");
            ddlEndTime.DataSource = timeList;
            ddlEndTime.DataBind();
            ddlEndTime.SelectedValue = DateTime.Parse(lbEndDT.Text).Hour.ToString();

            if (CalendarSchedule.SelectedDate.Date < DateTime.Now.Date) //选中时间小于当前日期，则为查阅历史
            {
                var lblFreq = (Label)e.Item.FindControl("lblFreq");
                var lblFreqPer = (Label)e.Item.FindControl("lblFreqPer");
                var ddlFreqNumber = (DropDownList)e.Item.FindControl("ddlFreqNumber");
                var ddlFreqType = (DropDownList)e.Item.FindControl("ddlFreqType");
                var tbDetails = (TextBox)e.Item.FindControl("tbDetails");
                var chbCare = (CheckBox)e.Item.FindControl("chbCare");

                lblFreq.Visible = false;
                lblFreqPer.Visible = false;
                ddlFreqNumber.Visible = false;
                ddlFreqType.Visible = false;

                chbCare.Enabled = false;
                ddlNurse.Enabled = false;
                ddlStartTime.Enabled = false;
                ddlEndTime.Enabled = false;
                tbDetails.Enabled = false;
            }

        }

        protected void ScheduleList_DataBinding(object sender, EventArgs e)
        {

        }

        protected void ScheduleList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void CalendarSchedule_SelectionChanged(object sender, EventArgs e)
        {
            CanledarSelectDate = CalendarSchedule.SelectedDate.Date;
            tbLoopEndDay.Text = CalendarSchedule.SelectedDate.Date.ToShortDateString();

            HiddenAddFamily();
            InitialTime();
            InitialNurseList();
            InitialSchedule();
        }

        protected void btnShowNewSchedule_Click(object sender, EventArgs e)
        {
            ShowSchedule();
            CreateNewSchedule();
        }

        protected void CalendarSchedule_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
        {
            HiddenAddFamily();
            InitialCalendar();
        }

        protected void CalendarSchedule_DayRender(object sender, DayRenderEventArgs e)
        {
            foreach (DateTime dt in bookedDateList)
            {
                if (e.Day.Date.Subtract(dt).Days == 0)
                {
                    e.Cell.BackColor = System.Drawing.Color.Green; //高亮显示的日期，背景色为红色。
                }
            }

            if (e.Day.IsOtherMonth)
            {
                e.Cell.Controls.Clear();
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();

            foreach (var item in ScheduleList.Items)
            {
                var chbCare = (CheckBox)((DataListItem)item).FindControl("chbCare");
                if (!chbCare.Checked)
                    continue;

                var lbScheduleId = (Label)((DataListItem)item).FindControl("lbScheduleId");

                var msg = new ScheduleMessage()
                {
                    Id = int.Parse(lbScheduleId.Text),
                };
                scheduleAdaptor.Remove(msg);
            }
            InitialCalendar();

            InitialTime();
            InitialNurseList();
            InitialSchedule();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();
            var loopEndDay = DateTime.Parse(tbLoopEndDay.Text);

            foreach (var item in ScheduleList.Items)
            {
                var chbCare = (CheckBox)((DataListItem)item).FindControl("chbCare");
                if (!chbCare.Checked)
                    continue;

                var ddlNurse = (DropDownList)((DataListItem)item).FindControl("ddlNurse");
                var lbScheduleId = (Label)((DataListItem)item).FindControl("lbScheduleId");
                var lbFamilyId = (Label)((DataListItem)item).FindControl("lbFamilyId");
                var lbStatus = (Label)((DataListItem)item).FindControl("lbStatus");
                var ddlStartTime = (DropDownList)((DataListItem)item).FindControl("ddlStartTime");
                var ddlEndTime = (DropDownList)((DataListItem)item).FindControl("ddlEndTime");
                var tbDetails = (TextBox)((DataListItem)item).FindControl("tbDetails");
                
                // 计算timespan
                var ddlFreqNumber = (DropDownList)((DataListItem)item).FindControl("ddlFreqNumber");
                var ddlFreqType = (DropDownList)((DataListItem)item).FindControl("ddlFreqType");
                var loopDays = default(double);
                var freqNumber = int.Parse(ddlFreqNumber.SelectedValue);
                switch (ddlFreqType.SelectedValue.ToUpper())
                {
                    case "MONTH":
                        loopDays = 30 * freqNumber;
                        break;
                    case "WEEK":
                        loopDays = 7 * freqNumber;
                        break;
                    case "DAY":
                        loopDays = 1 * freqNumber;
                        break;
                    default:break;
                }


                var msg = new ScheduleMessage()
                {
                    Id = int.Parse(lbScheduleId.Text),
                    NurseId = int.Parse(ddlNurse.SelectedValue),
                    FamilyId = int.Parse(lbFamilyId.Text),
                    ScheduleDay = CalendarSchedule.SelectedDate.Date,
                    LoopEndDay = loopEndDay,
                    LoopDays = loopDays,
                    StartDT = CalendarSchedule.SelectedDate.Date.AddHours(double.Parse(ddlStartTime.SelectedValue)),
                    EndDT = CalendarSchedule.SelectedDate.Date.AddHours(double.Parse(ddlEndTime.SelectedValue)),
                    Status = lbStatus.Text,
                    Details = tbDetails.Text
                };
                scheduleAdaptor.Update(msg);
            }
            InitialCalendar();
        }

        protected void btnSetPerson_Click(object sender, EventArgs e)
        {
            if (panelAddFamily.Visible)
            {
                HiddenAddFamily();
            }
            else
            {
                ShowAddFamily();
                InitialFamilyList();
            }
        }

        protected void btnAddFamily_Click(object sender, EventArgs e)
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();
            foreach (ListItem item in Familylist.Items)
            {
                if (!item.Selected) continue;
                var msg = new ScheduleMessage()
                              {
                                  FamilyId = int.Parse(item.Value),
                                  ScheduleDay = CalendarSchedule.SelectedDate.Date,
                                  Status = StatusTypes.TODO.ToString(),
                                  StartDT = CalendarSchedule.SelectedDate.Date,
                                  EndDT = CalendarSchedule.SelectedDate.Date,
                                  NurseId = -1,
                              };
                scheduleAdaptor.Update(msg);
            }

            InitialTime();
            InitialNurseList();
            InitialSchedule();

            InitialFamilyList();
        }

        protected void btnRefreshFamilyList_Click(object sender, EventArgs e)
        {
            InitialFamilyList();
        }
    }
}